#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
from typing import List

class ConfigValidator:
    """配置验证器"""

    def __init__(self):
        self.errors: List[str] = []
        self.valid_field_types = {'text', 'number', 'datetime', 'date', 'select'}

    def _validate_table_info(self, table_info: dict) -> bool:
        """验证表信息"""
        required_fields = {
            'chinese_name': '中文名称',
            'table_name': '表名',
            'entity_name': '实体名称',
            'class_name': '类名',
            'java_package_name': 'Java包名'
        }

        is_valid = True
        for field, name in required_fields.items():
            if field not in table_info:
                self.errors.append(f"表信息缺少{name}")
                is_valid = False
            elif not table_info[field]:
                self.errors.append(f"表信息的{name}不能为空")
                is_valid = False

        # 验证表名格式
        if 'table_name' in table_info:
            table_name = table_info['table_name']
            if not table_name.startswith('t_'):
                self.errors.append("表名必须以't_'开头")
                is_valid = False
            if not all(c.isalnum() or c == '_' for c in table_name):
                self.errors.append("表名只能包含字母、数字和下划线")
                is_valid = False

        return is_valid

    def _validate_column(self, column: dict, index: int) -> bool:
        """验证字段信息"""
        required_fields = {
            '字段中文名': '字段中文名',
            '字段名称': '字段名称',
            '字段类型': '字段类型',
            '是否可为空': '是否可为空',
            '是否显示': '是否显示',
            '是否可编辑': '是否可编辑'
        }

        is_valid = True
        for field, name in required_fields.items():
            if field not in column:
                self.errors.append(f"第{index+1}个字段缺少{name}")
                is_valid = False
            elif not column[field]:
                self.errors.append(f"第{index+1}个字段的{name}不能为空")
                is_valid = False

        # 验证字段类型
        if '字段类型' in column and column['字段类型'] not in self.valid_field_types:
            self.errors.append(f"第{index+1}个字段的类型'{column['字段类型']}'无效，必须是{', '.join(self.valid_field_types)}之一")
            is_valid = False

        # 验证布尔值字段
        bool_fields = ['是否可为空', '是否显示', '是否可编辑']
        for field in bool_fields:
            if field in column and column[field] not in ['true', 'false']:
                self.errors.append(f"第{index+1}个字段的{field}必须是'true'或'false'")
                is_valid = False

        # 验证字段名格式
        if '字段名称' in column:
            field_name = column['字段名称']
            if not all(c.isalnum() or c == '_' for c in field_name):
                self.errors.append(f"第{index+1}个字段的名称'{field_name}'只能包含字母、数字和下划线")
                is_valid = False

        return is_valid

    def validate(self, content: str) -> bool:
        """验证配置内容"""
        self.errors = []

        try:
            config = json.loads(content)
        except json.JSONDecodeError as e:
            self.errors.append(f"JSON格式错误: {str(e)}")
            return False

        is_valid = True

        # 验证基本结构
        if 'table_info' not in config:
            self.errors.append("缺少table_info配置")
            is_valid = False

        if 'columns' not in config:
            self.errors.append("缺少columns配置")
            is_valid = False
        elif not isinstance(config['columns'], list):
            self.errors.append("columns必须是数组")
            is_valid = False

        # 验证表信息
        if 'table_info' in config:
            if not self._validate_table_info(config['table_info']):
                is_valid = False

        # 验证字段信息
        if 'columns' in config and isinstance(config['columns'], list):
            if not config['columns']:
                self.errors.append("至少需要一个字段")
                is_valid = False
            else:
                for i, column in enumerate(config['columns']):
                    if not self._validate_column(column, i):
                        is_valid = False

        return is_valid